The FOREACH statement executes one or more statements for each element of a variable (which can be an array, list, or hash table). Within the FOREACH loop, the element’s value and (optionally) the index or key to which the element corresponds are available.
FOREACH Element, Variable [, Index] DO Statement
or
FOREACH Element, Variable [, Index] DO BEGIN
statements
ENDFOREACH
If Variable is an array or list, then the optional Index is set to an integer corresponding to the current loop index. If Variable is a hash, then Index is set to the key corresponding to the current key-value pair.
A simple FOREACH code example:
array = [1, 3, 5, 7, 9, 11, 13, 15]
FOREACH element, array DO PRINT, 'Value = ', element
This code sample produces the following output:
Value = 1
Value = 3
Value = 5
Value = 7
Value = 9
Value = 11
Value = 13
Value = 15
The same example, but also supplying the optional index argument:
array = [1, 3, 5, 7, 9, 11, 13, 15]
FOREACH element, array, index DO PRINT, 'Index ', index, ' Value = ', element
This code sample produces the following output:
Index 0 Value = 1
Index 1 Value = 3
Index 2 Value = 5
Index 3 Value = 7
Index 4 Value = 9
Index 5 Value = 11
Index 6 Value = 13
Index 7 Value = 15
The next example uses the block structure (instead of a single statement):
PRO testForeach
list = LIST(77.97, 'Galactic', [2, 7, 1, 8, 2])
FOREACH element, list DO BEGIN
PRINT, 'Value = ', element
ENDFOREACH
END
After compiling and running the procedure, it produces the following output:
Value = 77.9700
Value = Galactic
Value = 2 7 1 8 2
In a FOREACH statement, Variable can be an expression as well as a literal. In this example, we create a two-dimensional array and use an expression for Variable to print out the third column elements.
The 3x3 array elements are:
0 1 2
3 4 5
6 7 8
arr = INDGEN(3,3)
FOREACH element, arr[2,*] DO PRINT, element
IDL prints:
2
5
8
In this example, we create a hash table and loop through all of the key-value pairs.
planets = HASH('Mercury', 0.3e24, 'Venus', 5e24, $
'Earth', 6e24, 'Mars', 0.65e24, 'Jupiter', 1900e24, $
'Saturn', 570e24, 'Uranus', 87e24, 'Neptune', 100e24, $
'Pluto', 0.7e24)
FOREACH mass, planets, key DO PRINT, key, mass
IDL prints:
Mercury 3.00000e+023
Venus 5.00000e+024
Earth 6.00000e+024
Neptune 1.00000e+026
Saturn 5.70000e+026
Mars 6.50000e+023
Uranus 8.70000e+025
Pluto 7.00000e+023
Jupiter 1.90000e+027
Notice that the order in which the keys are returned is arbitrary for a hash table.
8.0 |
Introduced |
BEGIN...END , BREAK , CASE , CONTINUE , FOR , GOTO , IF...THEN...ELSE , REPEAT...UNTIL , SWITCH , WHILE...DO